#!/opt/homebrew/bin/python3
# -*- coding:utf-8 -*-
#modify by lank
#alias xy="python /opt/autologin/login.py "
#sshpass
import sys,os,time
import configparser
class Config:
    def __init__(self, path):
        self.path = path
        self.cf = configparser.ConfigParser()
        self.cf.read(self.path)
    def get(self, field, key):
        result = ""
        try:
            result = self.cf.get(field, key)
        except:
            result = ""
        return result
    def set(self, filed, key, value):
        try:
            self.cf.set(field, key, value)
            cf.write(open(self.path,'w'))
        except:
            return False
        return True

def read_config(config_file_path, field, key):
    cf = configparser.ConfigParser()
    try:
        cf.read(config_file_path)
        result = cf.get(field, key)
    except:
        sys.exit(1)
    return result

def write_config(config_file_path, field, key, value):
    cf = configparser.ConfigParser()
    try:
        cf.read(config_file_path)
        cf.set(field, key, value)
        cf.write(open(config_file_path,'w'))
    except:
        sys.exit(1)
    return True

def list_sections():
    cf = configparser.ConfigParser()
    try:
      cf.read(config_file_path)
      result = cf.sections()
    except:
      sys.exit(1)
    return result

def ssh_login(field):
    cf = configparser.ConfigParser()
    resdict={}
    try:
        cf.read(config_file_path)
        resdict["host"] = cf.get(field, 'host')
        resdict["user"] = cf.get(field, 'user')
        resdict["port"] = cf.get(field, 'port')
        resdict["pwd"] = cf.get(field, 'password')
    except:
      sys.exit(1)
    return resdict

def cur_file_dir():
     #获取脚本路径
     path = sys.path[0]
     if os.path.isdir(path):
         return path
     elif os.path.isfile(path):
         return os.path.dirname(path)

def list_section(field):
    cf = configparser.ConfigParser()
    try:
      cf.read(config_file_path)
      result = cf.items(field)
    except:
      sys.exit(1)
    return result

def conn(secion):
    dict = ssh_login(secion)
    os.system('sshpass -p '+dict["pwd"]+' ssh -A -p '+dict["port"]+'  -o StrictHostKeyChecking=no '+dict["user"]+'@'+dict["host"])

def listbak():
    data = list_sections()
    i = 0
    for item in data:
        print (' '+item+' ')
        if i == 3:
            i = 0
            print ('')
        else:
            i=i+1
def list():
    data = list_sections()
    i = 1
    for item in data:
        dict = ssh_login(item)
        print (str(i)+' \033[1;32m'+item+'\033[0m: \033[1;31m ssh -p '+dict["port"]+' '  +dict["user"]+'@'+dict["host"]+'\033[0m'+':/tmp ' +dict["pwd"])
        i=i+1


def list_info(parms):
    if len(parms) == 3:
        print (list_section(parms[2]))
    else:
        list()

def process(parms):

    cmd = parms[1];
    if cmd == 'conn':
        secion = parms[2]
        conn(secion)
    elif cmd == 'list':
        list_info(parms)
    elif cmd == 'i':
        list_info(parms)
    elif cmd == 'help':
        showhelp();
    else:
        if cmd.isdigit():
            data = list_sections()

            data_len=len(data);
            if(int(cmd)<=data_len&int(cmd)>0):
                print ('connect to '+data[int(cmd)-1])
                conn(data[int(cmd)-1])
        else:
            print ('connect to '+cmd)
            conn(cmd)
def showhelp():
    print ('--show help about command,as:')
    print ('    conn <alias_name>')
    print ('    list <alias_name>')


def verify(parms):
    if len(parms) <= 1:
        list()
        return False;
    return True

if __name__ == "__main__":
   config_file_path =  cur_file_dir()+'/login.ini'
   if verify(sys.argv):
       process(sys.argv)
